package com.my.socket.bio.v7;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.net.Socket;
import java.util.concurrent.BlockingQueue;

/**
 * Created by Scarlett on 2018/6/28 0028.
 */
public class SocketProcessor implements Runnable {
    private static final Logger LOGGER = LoggerFactory.getLogger(SocketProcessor.class);

    private BlockingQueue<Connection> queue;

    public SocketProcessor(BlockingQueue<Connection> queue) {
        this.queue = queue;
    }

    @Override
    public void run() {
        while (true) {
            Connection connection = null;
            try {
                connection = queue.take();
                Socket socket = connection.getSocket();

                InputStream inputStream = socket.getInputStream();
                BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
                String message = reader.readLine();
                LOGGER.info("thread: {}, read: {}", Thread.currentThread().getName(), message);

                OutputStream outputStream = socket.getOutputStream();
                BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream));
                writer.write(message);
                writer.flush();
                LOGGER.info("thread: {}, written: {}", Thread.currentThread().getName(), message);
            } catch (Exception e) {
                LOGGER.error("exception caught, the error is {}", e.getMessage());
                break;
            } finally {
                if (connection != null) {
                    connection.close();
                }
            }
        }
    }
}
